package com.haoe.controller;

import com.google.common.collect.Lists;
import com.haoe.common.CommonResult;
import com.haoe.dto.DishDTO;
import com.haoe.dto.query.OrderInfoQuery;
import com.haoe.dto.vo.OrderInfoVO;
import com.haoe.entity.Customer;
import com.haoe.entity.MenuDish;
import com.haoe.entity.Order;
import com.haoe.entity.OrderDish;
import com.haoe.enums.OrderStatusEnum;
import com.haoe.mapper.OrderDishMapper;
import com.haoe.service.CustomerService;
import com.haoe.service.MenuDishService;
import com.haoe.service.OrderDishService;
import com.haoe.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author: 80305082
 * @Date: 2021/3/12
 * @Description: 顾客controller层
 */
@RestController
@Slf4j
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDishService orderDishService;

    @Autowired
    private MenuDishService menuDishService;

    /**
     * 根据顾客id查询顾客信息:已测试
     *
     * @param id 顾客id
     * @return 顾客信息
     * @throws Exception 查询异常信息
     */
    @GetMapping("/id")
    public CommonResult<Customer> getCustomerById(@RequestParam("id") Long id) throws Exception {
        if (Objects.isNull(id)) {
            throw new Exception("用户Id不能为空，请重新输入");
        }

        Customer customer = customerService.getCustomerInfo(id);
        if (customer == null) {
            return CommonResult.success(null, "该顾客不存在");
        }
        log.info("customer = {}", customer);
        return CommonResult.success(customer);
    }

    /**
     * 顾客提交（创建）订单（修改事务，修改为批量插入数据 ）：已测试
     *
     * @param orderInfoQuery 请求订单详情
     * @return 提交结果
     * @throws Exception 提交异常信息
     */
    @PostMapping("/order")
    public CommonResult submitOrder(@RequestBody OrderInfoQuery orderInfoQuery) {
        if (Objects.isNull(orderInfoQuery)) {
            return CommonResult.validateFailed("没有订单信息");
        }
        CommonResult<Object> result;
        try {
            // TODO：验证订单信息（是否存在当前餐厅，是否存在当前菜单集合等） 目前暂时不做验证工作
            //  流程：1.创建订单 2. 获取创建订单生成的订单id以及orderInfo中的菜单集合信息，存入order_dish表
            result = customerService.submitOrder(orderInfoQuery);
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("提交订单失败:" + e.getMessage());
        }

        return result;
    }

    /**
     * 查询当前顾客的所有订单信息:已测试
     *
     * @param id 顾客id
     * @return 订单详情
     * @throws Exception 查询异常信息
     */
    @GetMapping("/customerId")
    public CommonResult<List<OrderInfoVO>> queryOrderById(@RequestParam("id") Long id) {
        List<OrderInfoVO> result = Lists.newArrayList();
        try {
            List<Order> orderList = orderService.selectByCustomerId(id);
            CommonResult<List<OrderInfoVO>> res = getOrderInfoResult(id, result, orderList);
            if (res != null) return res;
        } catch (Exception e) {
            log.error("顾客id：{} {}", id, e.getMessage());
            return CommonResult.failed("查询失败:" + e.getMessage());
        }

        return CommonResult.success(result);
    }

    public CommonResult<List<OrderInfoVO>> getOrderInfoResult(@RequestParam("id") Long id, List<OrderInfoVO> result, List<Order> orderList) throws Exception {
        if (orderList.isEmpty()) {
            return CommonResult.success(new ArrayList<>(), "不存在该顾客的订单");
        }
        // 查询order_dish表 获取每个订单的所有菜单
        if (getOrderInfo(id, result, orderList)) throw new Exception("查询订单信息异常");
        return null;
    }

    public boolean getOrderInfo(@RequestParam Long id, List<OrderInfoVO> result, List<Order> orderList) {
        for (Order order : orderList) {
            OrderInfoVO orderInfoVo = (OrderInfoVO) OrderInfoVO.builder().customerId(id).restaurantId(order.getRestaurantId()).createdOn(order.getCreatedOn()).status(order.getStatus()).build();
            List<OrderDish> orderDishList = orderDishService.selectByOrderId(order.getId());
            if (orderDishList.isEmpty()) {
                return true;
            }
            List<DishDTO> dishDTOList = Lists.newArrayList();
            for (OrderDish orderDish : orderDishList) {
                MenuDish menuDish = menuDishService.selectById(orderDish.getMenuDishId());
                DishDTO dishDto = DishDTO.builder().count(orderDish.getCount()).dish(menuDish).build();
                dishDTOList.add(dishDto);
            }

            orderInfoVo.setDishDTOList(dishDTOList);
            int money = 0;
            for (DishDTO dishDto : dishDTOList) {
                money += dishDto.getCount() * dishDto.getDish().getPrice();
            }
            orderInfoVo.setTotalPay(money);
            log.info("orderInfoVo:{}", orderInfoVo);
            result.add(orderInfoVo);
        }
        return false;
    }

    /**
     * 支付订单:已测试
     *
     * @param orderId 订单id
     * @param status  订单状态
     * @return 支付结果
     */
    @PostMapping("orderId/status")
    public CommonResult payOrder(@RequestParam("orderId") Long orderId, @RequestParam("status") Integer status) {
        // TODO ：1. 查询当前订单是否状态为0，若是，修改订单状态为3，表示下单（支付）成功；否则无法支付
        Order order = orderService.selectById(orderId);
        try {
            if (Objects.isNull(order)) {
                return CommonResult.failed("订单不存在");
            }
            if (order.getStatus() != OrderStatusEnum.SUBMIT.getCode()) {
                return CommonResult.failed("订单已生效，无法再次修改");
            }
            orderService.updateOrder(orderId, status);
        } catch (Exception e) {
            log.error("支付异常，请重试. 异常信息：{}", e.getMessage());
            return CommonResult.failed("支付异常");
        }
        return CommonResult.success(order);
    }

    /**
     * 修改未提交的订单 ： 已测试
     *
     * @param query 订单信息
     * @return 修改成功信息
     * @throws Exception 修改异常
     */
    @PostMapping("orderId/update")
    public CommonResult updateOrder(@RequestBody OrderInfoQuery query) throws Exception {
        // todo : 1. 根据订单的顾客id，餐厅id 状态为未支付，查询是否存在该订单 2. 重新提交修改后的订单信息
        try {
            Order submitOrder = orderService.selectByKeys(query.getCustomerId(), query.getRestaurantId(), OrderStatusEnum.SUBMIT.getCode());
            if (submitOrder == null) {
                return CommonResult.failed("不存在可以修改的订单");
            }
            // 只需要修改order_dish表信息即可：先根据order_id删除表中的记录，然后新增修改后的记录（query里的数据）
            int code = orderDishService.deleteByOrderId(submitOrder.getId());
            if (code <= 0) {
                log.error("删除订单，id：{} 记录失败", submitOrder.getId());
                return CommonResult.failed("修改失败");
            }
            // 批量插入
            customerService.batchSaveOrderDish(query, submitOrder.getId());
        } catch (Exception e) {
            log.error("修改订单异常：{}", e.getMessage());
            return CommonResult.failed("修改订单失败");
        }
        return CommonResult.success(null);
    }
}